package com.peppa.common.grayconfig.Strategy;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.peppa.common.grayconfig.FeignHeaderRequestInterceptor;
import com.peppa.common.grayconfig.Strategy.factory.AnnoStrategy;
import com.peppa.common.grayconfig.ThreadAttributes;

/**
 * @author     ：杜戈
 * @date       ：Created in 2019.08.21
 * @description：自动IP策略，如果调用方ip与某个服务器ip相同，则选择这个服务器
 */
@AnnoStrategy
public class AutoIpStrategy extends StrategyAbstract {

    public AutoIpStrategy() {
        setName(A_IP);
        setOrder(SORT_A_IP);
    }

    @Override
    public Server getServer(ILoadBalancer balancer){
        String ip = (String) ThreadAttributes.getThreadAttribute(FeignHeaderRequestInterceptor.HTTP_X_FORWARDED_FOR);
        if (ip == null || ip.equals("")){
            logger.info("HTTP_X_FORWARDED_FOR threadlocal ip:---null!!!");
            return null;
        }
        logger.info("HTTP_X_FORWARDED_FOR threadlocal ip:---{}",ip);
        return getIpSameServer(ip,balancer);
    }
    @Override
    public String getName(){
        return name;
    }
}
